package com.xhsj.user.security.filter;

import com.xhsj.user.security.ClientInfo;
import com.xhsj.user.security.IntegrationAuthentication;
import com.xhsj.user.security.IntegrationAuthenticationContext;
import com.xhsj.user.utils.RSACoder;
import com.xhsj.user.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author suxiaolin
 * @date 2020/4/10 15:40
 */
@Slf4j
@Component
public class IntegrationAuthenticationFilter extends OncePerRequestFilter implements ApplicationContextAware {

    @Value("${rsa.privateKey}")
    private String privateKey;

    private static final String AUTH_TYPE_PARM_NAME = "auth_type";

    private static final String OAUTH_TOKEN_URL = "/oauth/token";

    private ApplicationContext applicationContext;

    private RequestMatcher requestMatcher;

    public IntegrationAuthenticationFilter(){
        this.requestMatcher = new OrRequestMatcher(
                new AntPathRequestMatcher(OAUTH_TOKEN_URL, "GET"),
                new AntPathRequestMatcher(OAUTH_TOKEN_URL, "POST")
        );
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        if(requestMatcher.matches(request)){
            //设置集成登录信息
            String header = request.getHeader("auth_type");
            String random = request.getHeader("random");
            if (StringUtils.isBlank(header)) {
                header ="pwd";
            }
            log.info("header:{}",header);
            log.info("random:{}",random);
            System.err.println("random"+random);

            Map<String, String[]> parameterMap = request.getParameterMap();
            IntegrationAuthentication integrationAuthentication = new IntegrationAuthentication();
            integrationAuthentication.setAuthType(header);
            integrationAuthentication.setAuthParameters(request.getParameterMap());

            String username = "";
            String password = "";

            try {
                password = RSACoder.decrypt(integrationAuthentication.getAuthParameter("password"), privateKey);
                username = RSACoder.decrypt(integrationAuthentication.getAuthParameter("username"), privateKey);
            } catch (Exception e) {
                log.error("解密出错:{}",e);
                throw new OAuth2Exception("解密出错");
            }

            Map<String, String[]> m = new HashMap<String, String[]>(request.getParameterMap());
            m.put("grant_type", new String[] { "password" });
            m.put("client_id", new String[] { ClientInfo.CLIENT_ID });
            m.put("client_secret", new String[] { ClientInfo.CLIENT_SECRET });
            m.put("username", new String[] { username });
            m.put("password", new String[] { password });
            ParameterRequestWrapper wrapper = new ParameterRequestWrapper(request, m);

            integrationAuthentication.setAuthParameters(wrapper.getParameterMap());

            String msg= Base64.getEncoder().encodeToString("system:system".getBytes());
            wrapper.addHeader("Authorization","Basic "+msg);
            IntegrationAuthenticationContext.set(integrationAuthentication);

            try{
                //预处理
//                this.prepare(integrationAuthentication);

                filterChain.doFilter(wrapper,response);

                //后置处理
//                this.complete(integrationAuthentication);
            }finally {
                IntegrationAuthenticationContext.clear();
            }
        }else{
            filterChain.doFilter(request,response);
        }
    }

    /**
     * 进行预处理
     * @param
     */
//    private void prepare(IntegrationAuthentication integrationAuthentication) {
//
//        //延迟加载认证器
//        if(this.authenticators == null){
//            synchronized (this){
//                Map<String,IntegrationAuthenticator> integrationAuthenticatorMap = applicationContext.getBeansOfType(IntegrationAuthenticator.class);
//                if(integrationAuthenticatorMap != null){
//                    this.authenticators = integrationAuthenticatorMap.values();
//                }
//            }
//        }
//
//        if(this.authenticators == null){
//            this.authenticators = new ArrayList<>();
//        }
//
//        for (IntegrationAuthenticator authenticator: authenticators) {
//            if(authenticator.support(integrationAuthentication)){
//                authenticator.prepare(integrationAuthentication);
//            }
//        }
//    }

//    /**
//     * 后置处理
//     * @param integrationAuthentication
//     */
//    private void complete(IntegrationAuthentication integrationAuthentication){
//        for (IntegrationAuthenticator authenticator: authenticators) {
//            if(authenticator.support(integrationAuthentication)){
//                authenticator.complete(integrationAuthentication);
//            }
//        }
//    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}
